<template>
  <view :class="['content', { dark: theme == 'dark' }]">
    <view class="top"> </view>

    <view :class="['banner', 'funs', { darksss: theme == 'dark' }]">
      <dl>
        <dt>
          <image
            style="margin-top: 20px"
            src="../../static/logo.png"
            mode=""
          ></image>
        </dt>
      </dl>

      <view class="img">
        <!-- <savefile  :url="img" @hide="hidePhoto"></savefile> -->
        <image
          :src="img"
          mode=""
        ></image>
      </view>

      <view class="tgtit"
        ><text class="tugurl">{{ sourceLink }}</text></view
      >
      <view class="sharbuttn">
        <view
          class="btn"
          @click="savePic"
          >{{ $t('bico.W163') }}</view
        >
        <view
          class="btn"
          @click="sharurl"
          >{{ $t('bico.W164') }}</view
        >
      </view>

      <view class="shartitle">
        <view>{{ $t('bico.W165') }}</view>
      </view>

      <!-- <view class="sharapk" @click="share">
						<view><image src="../../static/img/Telegram.png"></image></view>
						<view><image src="../../static/img/weact.png"></image></view>
						<view><image src="../../static/img/shar.png"></image></view>
						<view><image src="../../static/img/qq.png"></image></view>
				</view> -->

      <!-- <view class="bottom">
        <ul>
          <li>{{ $t('bico.W166') }}</li>
          <li>{{ $t('bico.W167') }}</li>
          <li>{{ $t('bico.W168') }}</li>

          <li
            v-for="(item, i) in teamConfigList"
            :key="i"
          >
            {{ $t('bico.invi1') }}{{ item.number }}{{ $t('bico.invi2') }}{{ item.reward
            }}{{ item.coin }}
          </li>
        </ul>
      </view> -->
    </view>
  </view>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import QR from '@/common/qrcode.js';
import { info, teamRewardsListCommon } from '../../common/apiString.js';
import { myMixins } from '@/common/myMixins.js'; //加入全局下拉刷新
export default {
  mixins: [myMixins],
  data() {
    return {
      img: '../../static/img/ewm.jpg',
      providerList: [],
      sourceLink: '',
      type: 0,
      teamConfigList: []
    };
  },

  onLoad() {
    //下面一行就是设置上面标题的代码，复制修改括号里的标题，放在页面的onLoad()方法里最后面就可以了，
    this.$utils.setTitle(this.$t('bico.W162'));

    //下面这三行注释的代码
    // uni.setNavigationBarTitle({
    // 	title: this.$t('login').otc
    // })

    this.$utils.setTheme(this.theme);

    //this.version = plus.runtime.version;
    this.getUserInfo();
    this.getTeamConfigList();
    uni.getProvider({
      service: 'share',
      success: e => {
        let data = [];
        for (let i = 0; i < e.provider.length; i++) {
          switch (e.provider[i]) {
            case 'weixin':
              data.push({
                name: '分享 币商网 到 微信好友',
                id: 'weixin'
              });
              data.push({
                name: '分享 币商网 到 微信朋友圈',
                id: 'weixin',
                type: 'WXSenceTimeline'
              });
              break;

            case 'telegram':
              data.push({
                name: '分享到 币商网 到 Telegram',
                id: 'telegram'
              });
              break;

            case 'qq':
              data.push({
                name: '分享到 币商网 到 QQ',
                id: 'qq'
              });
              break;
            default:
              break;
          }
        }
        this.providerList = data;
      },
      fail: e => {
        console.log('获取登录通道失败' + JSON.stringify(e));
      }
    });
  },
  computed: {
    ...mapState({
      theme: state => state.theme
    })
  },
  methods: {
    hidePhoto() {
      this.isShowPhoto = false;
      uni.showToast({
        title: '图片已隐藏',
        icon: 'none'
      });
    },
    getUserInfo() {
      var that = this;
      this.$utils.initDataToken(
        {
          url: info,
          data: {},
          type: 'POST'
        },
        (res, msg) => {
          this.sourceLink = res.inviteLink;
          this.img = QR.createQrCodeImg(this.sourceLink);
        }
      );
    },
    getTeamConfigList() {
      var that = this;
      this.$utils.initData(
        {
          url: teamRewardsListCommon,
          data: {},
          type: 'POST'
        },
        (res, msg) => {
          this.teamConfigList = res;
        }
      );
    },
    //复制分享链接
    sharurl() {
      var that = this;
      uni.setClipboardData({
        data: this.sourceLink,
        success: function () {
          that.$utils.showLayer(that.$t('assets.copy_success'));
        },
        fail: function () {
          that.$utils.showLayer(that.$t('assets.copy_err'));
        }

        // success: function () {
        // 	console.log('success');
        // 	uni.showModal({
        // 		title: '复制成功',
        // 		content: '内容已复制到粘贴板，可前往其他应用粘贴查看。',
        // 		showCancel:false,
        // 		success: function(res) {
        // 			if (res.confirm) {
        // 	console.log('用户确定');
        // 			} else if (res.cancel) {
        // 				console.log('用户取消');
        // 			}
        // 		}
        // 	});
        // }
      });
    },
    //保存图片到相册
    save() {
      var that = this;
      uni.showActionSheet({
        itemList: ['保存图片到相册'],
        success: () => {
          that.andSave();
        }
      });
    },
    savePic() {
      var that = this;
      //#ifdef APP
      console.log('APP');
      that.save();
      //#endif
      //#ifdef H5
      console.log('H5');
      var Url = this.img; //图片路径，也可以传值进来
      var triggerEvent = 'touchstart'; //指定下载方式
      var blob = new Blob([''], {
        type: 'application/octet-stream'
      }); //二进制大型对象blob
      var url = URL.createObjectURL(blob); //创建一个字符串路径空位
      var a = document.createElement('a'); //创建一个 a 标签
      a.href = Url; //把路径赋到a标签的href上
      //正则表达式，这里是把图片文件名分离出来。拿到文件名赋到a.download,作为文件名来使用文本
      a.download = Url.replace(/(.*\/)*([^.]+.*)/gi, '$2').split('?')[0];
      /* var e = document.createEvent('MouseEvents');  //创建事件（MouseEvents鼠标事件）
				e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); //初始化鼠标事件（initMouseEvent已弃用）*/

      //代替方法。创建鼠标事件并初始化（后面这些参数我也不清楚，参考文档吧 https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent）
      var e = new MouseEvent(
        'click',
        (true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      );
      //派遣后，它将不再执行任何操作。执行保存到本地
      a.dispatchEvent(e);
      //释放一个已经存在的路径（有创建createObjectURL就要释放revokeObjectURL）
      URL.revokeObjectURL(url);
      //#endif
    },
    andSave() {
      let base64 = this.img;
      const bitmap = new plus.nativeObj.Bitmap('test');
      bitmap.loadBase64Data(
        base64,
        function () {
          const url = '_doc/' + new Date().getTime() + '.png'; // url为时间戳命名方式
          console.log('saveHeadImgFile', url);
          bitmap.save(
            url,
            {
              overwrite: true // 是否覆盖
              // quality: 'quality'  // 图片清晰度
            },
            i => {
              uni.saveImageToPhotosAlbum({
                filePath: url,
                success: function () {
                  uni.showToast({
                    title: '图片保存成功',
                    icon: 'none'
                  });
                  bitmap.clear();
                }
              });
            },
            e => {
              uni.showToast({
                title: '图片保存失败',
                icon: 'none'
              });
              bitmap.clear();
            }
          );
        },
        e => {
          uni.showToast({
            title: '图片保存失败',
            icon: 'none'
          });
          bitmap.clear();
        }
      );
    },

    share(e) {
      if (this.providerList.length === 0) {
        uni.showModal({
          title: '当前环境无分享渠道!',
          showCancel: false
        });
        return;
      }
      let itemList = this.providerList.map(function (value) {
        return value.name;
      });

      console.log(itemList);

      uni.showActionSheet({
        itemList: itemList,
        success: res => {
          console.log(this.providerList[res.tapIndex].id);
          if (this.providerList[res.tapIndex].id == 'qq') {
            this.type = 1;
          } else {
            this.type = 0;
          }
          uni.share({
            provider: this.providerList[res.tapIndex].id,
            scene:
              this.providerList[res.tapIndex].type &&
              this.providerList[res.tapIndex].type === 'WXSenceTimeline'
                ? 'WXSenceTimeline'
                : 'WXSceneSession',
            type: this.type,
            title: '耘助教',
            summary: '耘助教是一个在线教育应用平台',
            imageUrl: 'http://pds.jyt123.com/wxtest/logo.png',
            href: 'https://m3w.cn/uniapp',
            success: res => {
              console.log('success:' + JSON.stringify(res));
            },
            fail: e => {
              uni.showModal({
                content: e.errMsg,
                showCancel: false
              });
            }
          });
        }
      });
    },
    openLink() {
      plus.runtime.openWeb(this.sourceLink);
    }
  }
};
</script>

<style lang="scss">
.tugurl {
  color: #999;
}

.sharbuttn {
  display: flex;
  justify-content: center;
}

.shartitle {
  width: 80%;
  text-align: center;
  margin-left: 10%;
  border-bottom: 1px solid #dddddd;
  position: relative;
  height: 60upx;
}

.tgtit {
  text-align: center;
  margin-top: 10px;
}

.shartitle view {
  height: 50upx;
  line-height: 50upx;
  font-size: 28upx;
  color: #999;
  width: 120upx;
  margin: 32upx auto;
  position: absolute;
  background: #fff;
  left: 50%;
  margin-left: -60upx;
}

.sharapk {
  display: flex;
  justify-content: center;
  margin: 20upx auto;
}

.sharapk view {
  margin: 40upx;
}

.sharapk view image {
  height: 80upx;
  width: 80upx;
}

.content {
  width: 100%;
  background-color: #ffffff;
}

.top {
  width: 100%;
  height: 40vw;
  /* background: url(/static/img/banner.png) no-repeat; */
  background-color: #3e38ec;
  background-size: 100%;
  background-position: center center;
  border-radius: 0vw 0vw 4vw 4vw;
}

.banner {
  width: 92%;
  margin: 4vw;
  background-color: #ffffff;
  border-radius: 4vw 4vw 0 0;
  margin-top: -20vw;
}

.banner dl {
  margin-top: -80upx;
}

.banner dl dt {
  text-align: center;
}

.banner dl dt image {
  width: 160upx;
  height: 160upx;
  border-radius: 50%;
}

.banner dl dd {
  text-align: center;
}

.img {
  width: 300upx;
  height: 300upx;
  margin: 0 auto;
  margin-top: 60upx;
}

.img image {
  width: 100%;
  height: 100%;
}

.btn {
  width: 100px;
  height: 34px;
  line-height: 34px;
  margin: 0 auto;
  margin-top: 12px;
  border-radius: 4px;
  border: 0;
  font-size: 13px;
  outline: 0;
  background: #3e38ec;
  color: #ffffff;
  text-align: center;
}

.bottom {
  width: 100%;
  height: 400upx;
  /* background: url(/static/img/banner.png) no-repeat;
		background-position:left bottom; */
  background-size: 100%;
  margin-top: 30px;
}

.bottom ul {
  padding-left: 50px;
  box-sizing: border-box;
}

.bottom ul li {
  width: 100%;
  height: 60upx;
}
</style>
